<script setup>
import PageContainer from '@/components/pageContainer.vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { useUserStore } from '@/stores/index'
import { userUpdateAvatarService } from '@/api/user'
const UserStore = useUserStore()
const imageUrl = ref('')
imageUrl.value = UserStore.user.user_pic

//给button添加点击事件，触发upload的选择图片功能
const uploadRef = ref('')
// 用FileReader处理上传成功后的回调函数
const handleChange = (file) => {
  // 用FileReader读取图片做预览
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onloadend = () => {
    imageUrl.value = reader.result
  }
}

const uploadAvatar = async () => {
  console.log(4)
  await userUpdateAvatarService(imageUrl.value)
  await UserStore.getUser()
  console.log(2)
}
</script>
<template>
  <page-container title="更换头像">
    <el-upload
      :on-change="handleChange"
      ref="uploadRef"
      class="avatar-uploader"
      :show-file-list="false"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <el-button
      @click="uploadRef.$el.querySelector('input').click()"
      type="primary"
      :icon="Plus"
      size="large"
      >选择图片</el-button
    >
    <el-button @click="uploadAvatar" type="success" :icon="Upload" size="large"
      >上传头像</el-button
    >
  </page-container>
</template>
<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>
